$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'sys/activity/list',
        datatype: "json",
        colModel: [			
			{ label: 'id', name: 'id', index: 'id', width: 50, key: true,hidden:true },
			{ label: '活动名称', name: 'name', index: 'name', width: 80 }, 			
			{ label: '活动时间', name: 'start', index: 'start', width: 80,formatter: function(cellvalue, options, rowdata) {

                    return rowdata.start+" - "+rowdata.end;
                } },
			{ label: '发起分享数', name: 'sharenum', index: 'shareNum', width: 80 },
			{ label: '已领取数量', name: 'received', index: 'received', width: 80 },
			{ label: '剩余数量', name: 'surpluscount', index: 'surplusCount', width: 80 }, 			
			{ label: '状态', name: 'statu', index: 'statu', width: 80,formatter: function(item, index) {
                    if (item === 0) {
                        return '未开始';
                    }
                    if (item === 1) {
                        return '进行中';
                    }
                    if (item === 2) {
                        return '已结束';
                    }
                    if (item === 3) {
                        return '已停用';
                    }
                } },
            { label: '操作', name: 'sy', width: 70,align:'center',formatter: function(cellvalue, options, rowdata) {
                if(rowdata.statu == 2 ||rowdata.statu == 3){
                    return "<a style='cursor:pointer;' onclick='vm.getDetails("+ rowdata.id +")'>" +
                        "查看</a>";
                }else{
                    return "<a style='cursor:pointer;' onclick='vm.getDetails("+ rowdata.id +")'>" +
                        "查看</a>&nbsp;&nbsp;&nbsp;&nbsp;" +
                        "<a style='cursor:pointer;' onclick='vm.stopUsed("+ rowdata.id +")'>停用</a>";
                }

                }}
        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
});

var vm = new Vue({
	el:'#rrapp',
	data:{
		q:{
			name:null,
            statu:null
		},
		showList: true,
		title: null,
		activity: {},
        coupon:[]
	},
	methods: {
		query: function () {
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.activity = {};
			vm.activity.support = 0;
            $("#hdmc").removeAttr("readonly");
            $("#fxqs").removeAttr("readonly");
            $("#btnid").show();
            $("#saddon").show();
            $("#eaddon").show();
            $("#cz").show();
            $("#yhqbtn").show();
            vm.coupon = [];

            $("#coupons").html("");
            var temp ="<tr style='height:39px;'>" +
                    "<td colspan='6' style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);'>您还未选择货架</td>" +
                    "</tr>";

            $("#coupons").append(temp);


            var d = "<div style='width:46%;float:left;' class='input-group date'>" +
                "<input type='text' class='form-control' v-model='activity.start' id='astart'>" +
                "<span class='input-group-addon' id='saddon'><i class='glyphicon glyphicon-th'></i></span></div>" +
                "<div  style='width: 4%;float:left;margin-left:7px;margin-top:8px;padding-left:1px;'>-</div>" +
                "<div style='width:48%;' class='input-group date'>" +
                "<input type='text' class='form-control' v-model='activity.end' id='aend'>" +
                "<span class='input-group-addon' id='eaddon'><i class='glyphicon glyphicon-th'></i></span></div>";
            $("#container").html(d);
            $("#container .input-group.date").datepicker({
                language: "zh-CN",
                clearBtn: true, //清除按钮
                format: "yyyy-mm-dd",
                todayHighlight:true
            });
		},
		update: function (event) {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";
            
            vm.getInfo(id)
		},
        stopUsed: function (id) {

            vm.getInfo(id);
            console.log(vm.activity+"==========activity")
            vm.activity.statu = 3;
            $.ajax({
                type: "POST",
                url: baseURL + "sys/activity/update",
                contentType: "application/json",
                data: JSON.stringify(vm.activity),
                success: function(r){
                    if(r.code === 0){
                        alert('操作成功', function(index){
                            vm.reload();
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        addCoupon: function () {
            $("#jqGridAdd").jqGrid({
                url: baseURL + 'sys/coupon/list',
                datatype: "json",
                colModel: [
                    { label: 'id', name: 'id', index: 'id', width: 50, key: true,hidden:true },
                    { label: '优惠卷名称', name: 'name', index: 'name', width: 136 },
                    { label: '消费门槛', name: 'conditions', index: 'conditions', width: 123, width: 100,formatter: function(cellvalue, options, rowdata) {
                            var conditions = "";
                            if(rowdata.conditions == 0){
                                conditions = "无门槛";
                            }else{
                                conditions = "满"+rowdata.conditions+"元可用";
                            }
                            return conditions;
                        } },
                    { label: '有效期', name: 'effectivedays', index: 'effectivedays',width: 146,formatter: function(cellvalue, options, rowdata) {
                            if(rowdata.effectivedays == 0){
                                return rowdata.validitystar - rowdata.validityend;
                            }else{
                                return "领取当日"+rowdata.effectivedays+"天内有效";
                            }
                        }},
                    { label: '每人限领', name: 'limitcount', index: 'limitCount',width: 80},
                    { label: '库存', name: 'count', index: 'count',width: 80}

                ],
                viewrecords: true,
                height: 385,
                rowNum: 10,
                rowList : [10,30,50],
                rownumbers: true,
                rownumWidth: 25,
                autowidth:true,
                multiselect: true,
                pager: "#jqGridPagerAdd",
                jsonReader : {
                    root: "page.list",
                    page: "page.currPage",
                    total: "page.totalPage",
                    records: "page.totalCount"
                },
                prmNames : {
                    page:"page",
                    rows:"limit",
                    order: "order"
                },
                postData:{'statu':0},
                gridComplete:function(){
                    //隐藏grid底部滚动条
                    $("#jqGridPagerAdd").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
                }
            });
            $('#myModal').modal();
        },
        showCoupon:function () {
            var grid = $("#jqGridAdd");
            var rowKey = grid.getGridParam("selrow");
            if(!rowKey){
                alert("请选择一条记录");
                return ;
            }
            var rows = grid.getGridParam("selarrrow");

            var temp = "";
            $("#coupons").html("");
            for(var i=0;i<rows.length;i++){
                var obj = {};
                var isExits = false;
                if(vm.coupon.length>0){
                    for(var j=0;j<vm.coupon.length;j++){
                        if(rows[i]==vm.coupon[j].id){
                            isExits = true;
                        }
                    }
                    if(!isExits){
                        obj.id = rows[i];
                        obj.name = grid.getRowData(rows[i]).name;
                        obj.conditions = grid.getRowData(rows[i]).conditions;
                        obj.effectivedays = grid.getRowData(rows[i]).effectivedays;
                        obj.limitcount = grid.getRowData(rows[i]).limitcount;
                        obj.count = grid.getRowData(rows[i]).count;
                        vm.coupon.push(obj);

                    }

                }else{
                    obj.id = rows[i];
                    obj.name = grid.getRowData(rows[i]).name;
                    obj.conditions = grid.getRowData(rows[i]).conditions;
                    obj.effectivedays = grid.getRowData(rows[i]).effectivedays;
                    obj.limitcount = grid.getRowData(rows[i]).limitcount;
                    obj.count = grid.getRowData(rows[i]).count;
                    vm.coupon.push(obj);


                }

            }

            for(var k=0;k<vm.coupon.length;k++){

                temp +="<tr style='height:39px;' >" +
                    "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);'>"+vm.coupon[k].name+"</td>" +
                    "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>"+vm.coupon[k].conditions+"</td>" +
                    "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>"+vm.coupon[k].effectivedays+"</td>" +
                    "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>"+vm.coupon[k].limitcount+"</td>" +
                    "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>"+vm.coupon[k].count+"</td>" +
                    "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>" +
                    "<img src='../../statics/img/ico16-delete.png' onclick='vm.removeCoupon("+vm.coupon[k].id+")' style='cursor: pointer'></td></tr>";

            }
            $("#coupons").append(temp);
            $('#myModal').modal("hide");

        },
        removeCoupon: function (id) {
            var temp = "";
            $("#coupons").html("");
            var couponemp = [];
            for(var i=0;i<vm.coupon.length;i++){
                var obj = {};

                if(vm.coupon[i].id !=id){
                    obj.id = vm.coupon[i].id;
                    obj.name = vm.coupon[i].name;
                    obj.conditions = vm.coupon[i].conditions;
                    obj.effectivedays = vm.coupon[i].effectivedays;
                    obj.limitcount = vm.coupon[i].limitcount;
                    obj.count = vm.coupon[i].count;
                    couponemp.push(obj);


                    temp +="<tr style='height:39px;' >" +
                        "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);'>"+vm.coupon[i].name+"</td>" +
                        "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>"+vm.coupon[i].conditions+"</td>" +
                        "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>"+vm.coupon[i].effectivedays+"</td>" +
                        "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>"+vm.coupon[i].limitcount+"</td>" +
                        "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>"+vm.coupon[i].count+"</td>" +
                        "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>" +
                        "<img src='../../statics/img/ico16-delete.png' onclick='vm.removeCoupon("+vm.coupon[i].id+")' style='cursor: pointer'></td></tr>";
                }

            }

            vm.coupon = couponemp;
            if(vm.coupon.length==0){
                temp +="<tr style='height:39px;'>" +
                    "<td colspan='6' style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);'>您还未选择货架</td>" +
                    "</tr>";
            }
            $("#coupons").append(temp);
        },
        getDetails:function (id) {
            vm.getInfo(id);

            $("#coupons").html("");
            var couponidArray = vm.activity.couponid.split(",");
            var temp = "";

            for(var i=0;i<couponidArray.length;i++){
                $.ajax({
                    type: "POST",
                    async:false,
                    url: baseURL + "sys/coupon/info/"+couponidArray[i],
                    success: function(r){
                        console.log(r.coupon)
                        var conditions = "";
                        if(r.coupon.conditions == 0){
                            conditions = "无门槛";
                        }else{
                            conditions = "满"+r.coupon.conditions+"元可用";
                        }

                        var effectivedays = "";
                        if(r.coupon.effectivedays == 0){
                            effectivedays = r.coupon.validitystar - r.coupon.validityend;
                        }else{
                            effectivedays = "领取当日"+r.coupon.effectivedays+"天内有效";
                        }

                        temp +="<tr style='height:39px;' >" +
                            "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);'>"+r.coupon.name+"</td>" +
                            "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>"+conditions+"</td>" +
                            "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>"+effectivedays+"</td>" +
                            "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>"+r.coupon.limitcount+"</td>" +
                            "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>"+r.coupon.count+"</td></tr>";

                    }
                });
            }

            $("#coupons").html(temp);
            vm.showList = false;
            $("#hdmc").attr("readonly","readonly");
            $("#fxqs").attr("readonly","readonly");

            $("#btnid").hide();
            $("#saddon").hide();
            $("#eaddon").hide();
            $("#yhqbtn").hide();
            $("#cz").hide();
            var d = "<div style='width:46%;float:left;'>" +
                "<input type='text' class='form-control' value='"+vm.activity.start+"' id='astart' readonly='readonly'></div>" +
                "<div style='width: 4%;float:left;margin-left:7px;margin-top:8px;padding-left:1px;'>-</div>" +
                "<div style='width:48%;float:left;'>" +
                "<input type='text' class='form-control' value ='"+vm.activity.end+"' id='aend' readonly='readonly'></div>";
            $("#container").html(d);
        },
		saveOrUpdate: function (event) {
			var url = vm.activity.id == null ? "sys/activity/save" : "sys/activity/update";
            if(vm.activity.name =='' || typeof vm.activity.name=='undefined'){
                alert("活动名称不能为空");
            }else if(vm.activity.sharenum == '' ||typeof vm.activity.sharenum=='undefined'){
                alert("单次分享券数不能为空");
            }else if(vm.coupon.length ==0){
                alert("供分享的优惠券不能为空");
            }else{
                var couponid = "";
                var surpluscount = 0;
                for(var i=0;i<vm.coupon.length;i++){
                    couponid += vm.coupon[i].id;
                    if(i!=vm.coupon.length-1){
                        couponid += ",";
                    }
                    surpluscount +=parseInt(vm.coupon[i].count);
                }
                vm.activity.couponid = couponid;
                vm.activity.surpluscount = surpluscount;
                vm.activity.start = $("#astart").val();
                vm.activity.end = $("#aend").val();
                $.ajax({
                    type: "POST",
                    url: baseURL + url,
                    contentType: "application/json",
                    data: JSON.stringify(vm.activity),
                    success: function(r){
                        if(r.code === 0){
                            alert('操作成功', function(index){
                                vm.reload();
                                vm.coupon = [];
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            }

		},
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "sys/activity/delete",
                    contentType: "application/json",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(id){
            $.ajax({
                type: "POST",
                async:false,
                url: baseURL + "sys/activity/info/"+id,
                success: function(r){
                    vm.activity = r.activity;
                }
            });
		},
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{
                postData:{'name':vm.q.name,'statu':vm.q.statu},
                page:page
            }).trigger("reloadGrid");
		}
	}
});